﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media.Animation;
using GalaSoft.MvvmLight.Messaging;

namespace HP.Cachalote.WPF.Shared
{
    public class WindowBase : Window
    {
        private bool _windowCloseStoryBoardCompleted = false;

        public WindowBase()
        {
            RegisterMessages();

            Loaded += new RoutedEventHandler(WindowBase_Loaded);
            Unloaded += new RoutedEventHandler(WindowBase_Unloaded);
        }

        /// <summary>
        /// Register all necessary messages.
        /// </summary>
        protected virtual void RegisterMessages() { }

        protected override void OnMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);
            DragMove();
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e);

            // When window is closing and StoryboardHideWindow is not completed yet.
            if (!_windowCloseStoryBoardCompleted)
            {
                e.Cancel = true;

                var storyboardHideWindow = FindResource("StoryboardHideWindow") as Storyboard;
                storyboardHideWindow.Completed += new EventHandler(storyboardHideWindow_Completed);
                storyboardHideWindow.Begin();
            }
        }

        /// <summary>
        /// Get the message to close current window.
        /// </summary>
        /// <param name="messageToken">The message token to identify which window will be closed.</param>
        protected virtual void RegisterCloseWindowMessage(string messageToken)
        {
            Messenger.Default.Register<int>(this, messageToken, p =>
            {
                Close();
            });
        }

        protected virtual void WindowBase_Loaded(object sender, RoutedEventArgs e)
        {
            var storyboardShowWindow = FindResource("StoryboardShowWindow") as Storyboard;
            storyboardShowWindow.Begin();
        }

        protected virtual void WindowBase_Unloaded(object sender, RoutedEventArgs e)
        {
            // Cleanup in View.
            Messenger.Default.Unregister(this);

            // Cleanup in ViewModel.
            var viewModel = DataContext as MyViewModelBase;

            if (viewModel != null)
            {
                viewModel.Cleanup();
            }
        }

        private void storyboardHideWindow_Completed(object sender, EventArgs e)
        {
            // When StoryboardHideWindow is completed then window can be closed.
            _windowCloseStoryBoardCompleted = true;
            Close();
        }
    }
}
